%%%-------------------------------------------------------------------
%%% @author Anil Kumar S. R. <sranil@gmail.com>
%%% @copyright (C) 2010, 
%%% @doc
%%%
%%% @end
%%% Created : 16 Oct 2010 by Anil Kumar S. R. <sranil@gmail.com>
%%%-------------------------------------------------------------------
-module(port_manager).
-export([start/0, get_port/0]).

-include_lib("stdlib/include/qlc.hrl").

-record(port_state, {port_type, port}).

start() ->
    mnesia:create_table(port_state, 
                        [{ram_copies, [node()]}, {attributes, record_info(fields, port_state)}]),
    mnesia:wait_for_tables([port_state], 20000),
    mnesia:transaction(
      fun() ->
              mnesia:write(#port_state{port_type = rtp, port = 10000})
      end).

get_port() ->
    R = mnesia:transaction(
          fun() ->
                  [R] = mnesia:read({port_state, rtp}),
                  if
                      R#port_state.port >= 65000 ->
                          Next_Port = 10000;
                      true ->
                          Next_Port = R#port_state.port + 2
                  end,
                  mnesia:write(#port_state{port_type = rtp, port = Next_Port}),
                  R
          end),
    case R of
        {atomic, {port_state, rtp, Port}} ->
            {ok, Port};
        _ ->
            error
    end.
